<template>
  <section class="app-container">
    <!--工具条-->
    <el-col :span="24" class="toolbar" style="padding-bottom: 0px;">
      <el-form :inline="true" :model="filters" @submit.native.prevent>
        <el-form-item>
          <el-input v-model="filters.name" placeholder="赛事名称"></el-input>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" v-on:click="getTeam">查询</el-button>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handleAdd">报名</el-button>
        </el-form-item>
        <el-button type="danger" @click="batchRemove" :disabled="this.sels.length===0">批量删除</el-button>
      </el-form>
    </el-col>


    <!--列表-->
    <el-table :data="teamData" highlight-current-row @selection-change="selsChange" style="width: 100%;">
      <el-table-column type="selection" width="55">
      </el-table-column>
      <el-table-column type="index" width="60">
      </el-table-column>
      <el-table-column prop="id" label="编号" min-width="120">
      </el-table-column>
      <el-table-column prop="name" label="赛事名称" min-width="120">
      </el-table-column>
      <el-table-column prop="projectId" label="项目编号" min-width="100" >
      </el-table-column>
      <el-table-column prop="teamNo" label="团队编号" min-width="120">
      </el-table-column>
      <el-table-column prop="enrollTime" label="注册时间" min-width="120">
      </el-table-column>

      <el-table-column label="操作" width="200">
        <template slot-scope="scope">
          <el-button size="small" @click="handleEdit(scope.$index, scope.row)">编辑</el-button>
          <el-button size="small" type="success" @click="handleDetail(scope.$index, scope.row)">详情</el-button>
        </template>

      </el-table-column>
    </el-table>
    <!--分页工具-->
    <el-pagination
      background
      @size-change="handleSizeChange"
      :current-page="page"
      @current-change="handleCurrentChange"
      :page-sizes="[10, 20, 50, 100]"
      :page-size="limit"
      layout="total, sizes, prev, pager, next, jumper"
      :total="total">
    </el-pagination>


    <!--编辑界面-->
    <el-dialog
      :title="textMap[dialogStatus]"
      width="60%"
      height="60%"
       :visible.sync="dialogFormVisible"
       :close-on-click-modal="false">
      <el-form :model="editForm" label-width="120px" :rules="editFormRules" ref="editForm">
        <el-row>
          <el-col :span="8">
          <el-form-item label="赛事名称" >
            <el-select v-model="competitionName" :disabled="dialogStatus == 'detail'" filterable placeholder="请选择赛事名称">
              <el-option
                v-for="item in projectList"
                :key="item.name"
                :label="item.name"
                :value="item.name">
              </el-option>
            </el-select>
          </el-form-item>
          </el-col>
          <el-col :span="6">
          <el-form-item label="项目编号" prop="projectId">
            <el-select v-model="editForm.projectId" :disabled="dialogStatus == 'detail'" filterable placeholder="请选择项目编号">
              <el-option
                v-for="item in projectData"
                :key="item.projectId"
                :label="item.projectId"
                :value="item.projectId">
              </el-option>
            </el-select>
          </el-form-item>
          </el-col>

          <el-col :span="8">
              <el-form-item label="注册时间">
                <el-date-picker v-show="dialogStatus != 'detail'"
                    v-model="editForm.enrollTime"
                    type="datetime"
                    placeholder="选择日期时间">
                </el-date-picker>
                <el-input v-model="editForm.enrollTime" v-show="dialogStatus == 'detail'" disabled auto-complete="off" style="width: 220px;"></el-input>
              </el-form-item>
            <el-button type="primary" style="margin-left: 20px;" v-show="dialogStatus != 'detail'" @click="handleAddTeam">添加团队成员</el-button>
          </el-col>
        </el-row>
        <el-table :data="memberData" highlight-current-row  style="width: 100%;">
          <el-table-column type="index" width="30">
          </el-table-column>
          <!--<el-table-column prop="teamNo" label="团队编号" min-width="120">
          </el-table-column>-->
          <el-table-column prop="studentNo" label="学生学号" min-width="80">
          </el-table-column>
          <el-table-column prop="studentName" label="学生姓名" min-width="80">
          </el-table-column>
          <el-table-column prop="collegeName" label="所属学院" min-width="120">
          </el-table-column>
          <el-table-column prop="className" label="班级名称" min-width="120">
          </el-table-column>
          <el-table-column prop="grade" label="年级" min-width="100">
          </el-table-column>
          <el-table-column prop="major" label="专业" min-width="100">
          </el-table-column>
          <el-table-column prop="mail" label="邮箱" min-width="120">
          </el-table-column>
          <el-table-column prop="mobileNumber" label="手机号码" min-width="120">
          </el-table-column>
          <el-table-column
            fixed="right"
            label="操作"
            width="180"
            v-show="dialogStatus != 'detail'">
            <template slot-scope="scope" v-show="dialogStatus != 'detail'" >
              <el-button size="small" v-show="dialogStatus != 'detail'" @click="memberEdit(scope.$index, scope.row)">编辑</el-button>
              <el-button type="danger" v-show="dialogStatus != 'detail'" size="small" @click="memberDel(scope.$index, scope.row)">删除</el-button>
            </template>
          </el-table-column>
        </el-table>
      </el-form>
      <el-dialog
        width="45%"
        title="团队成员信息"
        :visible.sync="innerVisible"
        append-to-body>
        <el-form :model="member" label-width="80px" :rules="memberRules" ref="member">
          <el-row>
            <el-col :span="12">
            <el-form-item label="学号" prop="studentNo">
              <el-input v-model="member.studentNo" :disabled="dialogStatus == 'detail'" auto-complete="off" style="width: 220px;"></el-input>
            </el-form-item>
            <el-form-item label="学生姓名" prop="studentName">
              <el-input  v-model="member.studentName" :disabled="dialogStatus == 'detail'" auto-complete="off" style="width: 220px;"></el-input>
            </el-form-item>
            <el-form-item label="所属学院" prop="collegeName">
              <el-input v-model="member.collegeName" :disabled="dialogStatus == 'detail'" disabledauto-complete="off" style="width: 220px;"></el-input>
            </el-form-item>
            <el-form-item label="班级名称" prop="className">
              <el-input  v-model="member.className" :disabled="dialogStatus == 'detail'" auto-complete="off" style="width: 220px;"></el-input>
            </el-form-item>
            </el-col>

            <el-col :span="10">
            <el-form-item label="年级" prop="grade">
              <el-input v-model="member.grade" :disabled="dialogStatus == 'detail'" auto-complete="off" style="width: 220px;"></el-input>
            </el-form-item>
            <el-form-item label="专业" prop="major">
              <el-input v-model="member.major" :disabled="dialogStatus == 'detail'" auto-complete="off" style="width: 220px;"></el-input>
            </el-form-item>
            <el-form-item label="邮箱" prop="mail">
              <el-input v-model="member.mail" :disabled="dialogStatus == 'detail'" auto-complete="off" style="width: 220px;"></el-input>
            </el-form-item>
            <el-form-item label="手机号码" prop="mobileNumber">
              <el-input v-model="member.mobileNumber" :disabled="dialogStatus == 'detail'" auto-complete="off" style="width: 220px;"></el-input>
            </el-form-item>
            </el-col>

          </el-row>
        </el-form>
        <div slot="footer" class="dialog-footer">
          <el-button @click="innerVisible = false">取 消</el-button>
          <el-button type="primary" v-show="memberStatus == 'add'"  @click="addMember">添 加</el-button>
          <el-button type="primary" v-show="memberStatus == 'update'"  @click="editMember">修 改</el-button>
        </div>
      </el-dialog>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogFormVisible = false">取 消</el-button>
        <el-button type="primary" v-show="dialogStatus != 'detail'" @click="teamSave">保 存</el-button>
      </div>
    </el-dialog>



  </section>
</template>

<script>
  import Vue from 'vue'
  import {dateFormat} from "../../utils/dateFomat";

    export default {
      data(){
        return{
          teamData:[],   // 通过后台获取的团队数据
          memberList:[], // 添加的团队成员信息
          projectList:[],  // 通过审核的项目信息
          memberData:[],  // 团队成员信息存储
          memberIndex:0,   // 当前选中团队成员的索引
          member:{        // 单个团队成员信息
            teamNo:"",
            studentNo:"",
            studentName:"",
            collegeName:"",
            className:"",
            grade:"",
            major:"",
            mail:"",
            mobileNumber:"",
          },
          total: 0,
          page: 1,  // 当前页
          limit: 10,  // 每页数量
          projectData: [],  // 存储项目信息
          competitionName:"", // 选择的赛事名称
          sels: [], // 列表选中列
          filters: {
            name: ''
          },
          dialogStatus:"",
          memberStatus:"",
          dialogFormVisible: false,
          innerVisible:false,
          textMap: {
            update: '团队信息修改',
            add: '添加团队',
            detail: "团队详情",
            // examine: "项目立项审核",
          },
          // 编辑界面数据
          editForm: {
            id:0,
            name:"",
            projectId:"",
            teamNo:"",
            enrollTime:"",

            memberNo:"",
            studentNo:"",
            studentName:"",
            collegeName:"",
            className:"",
            grade:"",
            major:"",
            mail:"",
            mobileNumber:"",
          },
          // 数据校验
          editFormRules: {
            competitionName: [{required: true, message: '请选择赛事名称', trigger: 'blur'}],
            // name: [{required: true, message: '请选择赛事名称', trigger: 'blur'}],
            projectId: [{required: true, message: '请输入项目编号', trigger: 'blur'}],
            teamNo: [{required: true, message: '请输入团队编号', trigger: 'blur'}],
          },
          memberRules:{
            studentNo: [{required: true, message: '请输入学生学号', trigger: 'blur'}],
            studentName: [{required: true, message: '请输入学生姓名', trigger: 'blur'}],
            className: [{required: true, message: '请输入班级名称', trigger: 'blur'}],
            collegeName: [{required: true, message: '请输入所属学院', trigger: 'blur'}],
            grade: [{required: true, message: '请输入年级', trigger: 'blur'}],
            major: [{required: true, message: '请输入专业', trigger: 'blur'}],
            mail: [{required: true, message: '请输入邮箱', trigger: 'blur'}],
            mobileNumber: [{required: true, message: '请输入手机号码', trigger: 'blur'}],
          },
        }

      },
      watch:{
        // 监听选中的赛事名称
        competitionName(value) {
          this.projectData = [];
          this.projectList.forEach((obj) => {
            if (obj.name == value) {
              this.projectData.push(obj);
            }
          });
        },
      },
      mounted(){
       this.getTeam();
       this.getProject();
      },
      methods:{
        // 查询团队信息
        getTeam: function () {
          let teacher = localStorage.getItem("teacherId");
          if (teacher === 'undefined' || teacher === 'null' || teacher === undefined || teacher === null){
            teacher = "";
          }
          var _this = this;
          $.ajax({
            url: "http://47.100.49.86:8888/subject_competition/json/Team_list.action",
            // url: "http://localhost:8080/subject_competition/json/Team_list.action",
            type: "post",
            dataType: "json",
            data: {
              name: this.filters.name,
              page: this.page,
              limit: this.limit,
              teacherNo: teacher,
            },
            success: function (res) {
              _this.teamData = res.team;
              _this.memberList = res.member;
              _this.total = res.count;
            }
          });
        },

        // 查询项目立项信息
        getProject: function () {
          let charge = localStorage.getItem("teacherId");
          // 判断当前用户是否是教师
          if (charge === 'undefined' || charge === 'null' || charge === undefined || charge === null){
              charge = "";
          }
          var _this = this;
          $.ajax({
            url: "http://47.100.49.86:8888/subject_competition/json/ProjectApply_list.action",
            // url: "http://localhost:8080/subject_competition/json/ProjectApply_list.action",
            type: "post",
            dataType: "json",
            data: {
              status:"3",
              name: this.filters.name,
              page: this.page,
              limit: this.limit,
              charge:charge,
            },
            success: function (res) {
              _this.projectList = res.data;
            }
          });
        },
        // 保存or更新成员信息
        teamSave(){
          let flag = true;
          let saveFlag = '2';
          this.$refs.editForm.validate(valid => {
            if (valid) {
              this.$confirm('确认提交吗？', '提示', {})
                .then(() => {
                  if (this.memberData != "" && this.memberData.length != 0) {
                    const para = Object.assign({}, this.editForm)
                    if (this.dialogStatus === "update") {
                      saveFlag = '1';
                    }
                    if (this.dialogStatus == "add" || para.enrollTime != this.editForm.enrollTime) {
                      this.editForm.enrollTime = dateFormat.formatDate(this.editForm.enrollTime, "yyyy-MM-dd hh:mm:ss");
                    }
                    let _this = this;
                    $.ajax({
                      url: "http://47.100.49.86:8888/subject_competition/json/Team_saveOrUpdate.action",
                      // url: "http://localhost:8080/subject_competition/json/Team_saveOrUpdate.action",
                      data: {
                        id: this.editForm.id,
                        name: this.competitionName,
                        projectId: this.editForm.projectId,
                        teamNo: this.editForm.teamNo,
                        enrollTime: this.editForm.enrollTime,
                      },
                      dataType: "json",
                      async: false,
                      type: "post",
                      success: function (res) {
                        if (res.code === 0) {// 保存成功
                          _this.memberData.forEach((obj) => {
                            obj.teamNo = res.teamNo;
                          });
                        } else {  // 保存失败
                          flag = false;
                        }
                      }
                    });
                    let teacher = localStorage.getItem("teacherId");
                    // 判断当前用户是否是教师
                    if (teacher === 'undefined' || teacher === 'null' || teacher === undefined || teacher === null){
                      teacher = "";
                    }
                    if (flag) {
                      $.ajax({
                        url: "http://47.100.49.86:8888/subject_competition/json/TeamMember_batch.action",
                        // url: "http://localhost:8080/subject_competition/json/TeamMember_batch.action",
                        data: {
                          data: JSON.stringify(this.memberData),
                          teacherNo: teacher,
                        },
                        dataType: "json",
                        async: false,
                        type: "post",
                        success: function (res) {
                          if (res.code === 0) {
                            _this.dialogFormVisible = false;
                            _this.getTeam();
                            Vue.prototype.$message({
                              message: "操作成功",
                              type: 'success'
                            });
                          } else {
                            flag = false;
                            Vue.prototype.$message({
                              message: "操作失败",
                              type: 'error'
                            });
                          }
                        }
                      })
                    } else {
                      Vue.prototype.$message({
                        message: "操作失败",
                        type: 'error'
                      });
                    }
                  }else {
                    Vue.prototype.$message({
                      message: "请先添加团队成员",
                      type: 'error'
                    });
                  }

                });
            }
          });
        },
        // 添加团队成员
        addMember(){
          this.$refs.member.validate(valid => {
            if (valid) {
              this.$confirm('确认添加吗？', '提示', {})
                .then(() => {
                  this.memberData.push(this.member);
                  this.innerVisible = false;
                });
            }
          }).catch(() => { })
        },
        // 显示新增界面
        handleAdd: function () {
          this.dialogStatus = 'add'
          this.dialogFormVisible = true;
          // 置空
          this.memberData = [];
          this.editForm = {};
        },
        handleAddTeam(){
          this.memberStatus = "add";
          this.innerVisible = true;
          this.member = {};
        },
        // 显示编辑界面
        handleEdit(index, row) {
          this.memberData = [];
          this.dialogStatus = 'update'
          this.dialogFormVisible = true;
          console.log("list" + JSON.stringify(this.memberList));
          this.memberList.forEach((obj)=>{
            if(row.teamNo === obj.teamNo){
                this.memberData.push(obj);
            }
          });
          this.competitionName = row.name;
          this.editForm = Object.assign({}, row)
        },
        // 显示详情框
        handleDetail(index, row){
          this.dialogStatus = 'detail';
          this.dialogFormVisible = true;
          this.memberData = [];
          this.memberList.forEach((obj)=>{
            if(row.teamNo === obj.teamNo){
              this.memberData.push(obj);
            }
          });
          this.competitionName = row.name;
          this.editForm = Object.assign({}, row);
        },
        // 显示成员编辑界面
        memberEdit(index, row) {
          this.memberStatus = 'update'
          this.innerVisible = true;
          this.member = row;

          this.memberIndex = index;
          // this.editForm = Object.assign({}, row);
        },
        // 修改团队成员信息
        editMember(){
          this.memberData[this.memberIndex] = this.member;
          this.innerVisible = false;
        },
        // 全选单选多选
        selsChange(sels) {
          this.sels = sels
        },
        // 跳转到某页
        handleCurrentChange(val) {
          // 获取当前页
          this.page = val;
          // 重新获取数据
          this.getTeam();
        },
        // 改变每页条数
        handleSizeChange(val){
          this.limit = val;
          this.getTeam();
        },
        // 删除团队成员信息
        memberDel(index, row){
          if (this.dialogStatus === 'add'){
            this.memberData.splice(index);
            Vue.prototype.$message({
              message: "删除成功",
              type: 'success'
            });
          } else if (this.dialogStatus === 'update') {
            let _this = this;
            $.ajax({
              url:"http://47.100.49.86:8888/subject_competition/json/TeamMember_delete.action",
              // url:"http://localhost:8080/subject_competition/json/TeamMember_delete.action",
              type:"post",
              dataType:"json",
              data:{
                ids:"[" + JSON.stringify(row) + "]"
              },
              success:function (res) {
                if (res.code === 0){
                  // _this.getTeam();
                  _this.memberData.splice(index);
                  Vue.prototype.$message({
                    message: "删除成功",
                    type: 'success'
                  });
                } else {
                  Vue.prototype.$message({
                    message: "删除失败",
                    type: 'error'
                  });
                }
              }


            });
          }
        },
        // 批量删除
        batchRemove(){
          let flag = true;
          var _this = this;
          this.$confirm('确认删除选中记录吗？', '提示', {
            type: 'warning'
          }).then(() => {
              this.sels.forEach((sels)=>{
                  this.memberList.forEach((obj)=>{
                    console.log("item" + sels.teamNo + "=obj=member=" + obj.teamNo);
                    if(sels.teamNo == obj.teamNo) {
                      this.memberData.push(obj);
                    }
                  });
              });

            $.ajax({
              url: "http://47.100.49.86:8888/subject_competition/json/TeamMember_delete.action",
              // url: "http://localhost:8080/subject_competition/json/TeamMember_delete.action",
              type: "post",
              dataType: "json",
              async:false,
              data: {
                ids: JSON.stringify(this.memberData)
              },
              success: function (res) {
                if (res.code === 0) {
                }else {
                  flag = false;
                }
              }
            });

            if (flag) {
              $.ajax({
                url: "http://47.100.49.86:8888/subject_competition/json/Team_delete.action",
                // url: "http://localhost:8080/subject_competition/json/Team_delete.action",
                type: "post",
                dataType: "json",
                async: false,
                data: {
                  ids: JSON.stringify(this.sels)
                },
                success: function (res) {
                  if (res.code === 0) {
                    _this.getTeam();
                    Vue.prototype.$message({
                      message: "删除成功",
                      type: 'success'
                    });
                  } else {
                    Vue.prototype.$message({
                      message: "删除失败",
                      type: 'error'
                    });
                  }
                }
              });
            }else{
              Vue.prototype.$message({
                message: "删除失败",
                type: 'error'
              });
            }

          }).catch(() => {
            console.log("cancel");
          });


        },


      },
    }
</script>

<style scoped>

</style>
